package com.captain.leetcode.二分查找;

/**
 * Des:
 *
 * @author XL
 * @Date 2021/8/3 8:31
 */
public class 二分查找一个数 {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7};
        System.out.println(new 二分查找一个数().searchNum(arr, 3));
    }

    //Although the basic idea of binary search is comparatively straightforward, the details can be surprisingly tricky...
    public int searchNum(int[] nums, int target) {
        // 1 , 2, 3 ,4 ,5 ,6 ,7
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) return mid;
            else if (target > nums[mid]) left = mid + 1;
            else if (target < nums[mid]) right = right - 1;
        }
        return -1;
    }
}
